<template>
  <div class="page-appsale">
    <el-form label-position="top" :rules="rules" ref="ruleForm" :model="form">
      <div class="title">
        填写出售基本信息
      </div>
      <div class="sale-item">
        <div class="sale-row">
          <el-form-item label="仓库" prop="storageId">
            <el-select v-model="form.storageId" filterable   placeholder="选择仓库" @change="getTableData">
              <el-option v-for="item in storageOption" :key="item.id" :label="item.storageName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交易对象" prop="buyerId" >
            <el-select v-model="form.buyerId" filterable  placeholder="请选择">
              <el-option v-for="item in buyerOption" :key="item.buyerId" :label="item.buyerName" :value="item.buyerId"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="sale-row">
          <el-form-item label="回购期限(15~90天)" prop="repurchaseDays"  >
            <el-input v-model="form.repurchaseDays" placeholder="输入回购期限" maxlength="3" @blur="checkDays"></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="appsale-box" v-if="tableData.length > 0">
      <div class="appsale-title">
        选择要出售的货物
      </div>
      <egrid class="egrid-class" border
             :data="tableData"
             :columns="goodsColumns"
             propSpan="wrId"
             column-type="selection"
             @selection-change="handleSelectionChange"
             :columns-schema="columnsSchema"
             :columns-props="columnsProps">
      </egrid>
    </div>
    <div v-show="noData" class="no-data">
      暂无数据
    </div>
    <div class="submit-btn-box" v-if="tableData.length > 0">
      <a class="ml-btn-default w140 " @click="toPreview">预览</a>
    </div>
    <pc-dialog :is-show="isAppSalPre"  title ='出售预览' @on-close="isAppSalPre = false">
      <div >
        <AppSalePView :previewData="previewData" :form="form" @closeRefresh="closeRefresh"></AppSalePView>
      </div>
    </pc-dialog>
    <pc-dialog :is-show="isBillDetail"  title ='仓单详情' @on-close="isBillDetail = false">
      <div >
        <bill-detail :id="wrId"></bill-detail>
      </div>
    </pc-dialog>
  </div>
</template>
<script>
  import PcDialog from 'components/dialog';
  import AppSalePView from 'src/views/wms/trade/buy-back/appSalePView';
  import BillDetail from 'src/views/wms/dataquery/billlist/billManagement/billDetail';
  import mValidate from 'utils/common-method/validate/index';
  let that;
  // 操作按钮
  var Btn = {
    template: `<div style="text-align: center">
        <el-button type="primary" plain @click="viewdetail(row)">查看</el-button>
      </div>`,
    props: ['row'],
    computed: {},
    methods: {
      // 查看仓单详情
      viewdetail(val) {
        this.$emit('view-detail', val);
      }
    }
  };

  var Editor = {
    template: `<div style="text-align: center">
           <el-input maxlength="8" type="text"
           @blur="verifyInteger(row, column);convertToNumber(row, column)"
           v-model="row[column.property]"  :disabled="!row.selected"></el-input>
     </div>`,
    props: ['row', 'column'],
    computed: {},
    methods: {
      // 控制职能输入数字和小数点
      verifyInteger(row, column) {
        this.$emit('verify-integer', row, column);
      },
      // 将数字字符串转换成数字
      convertToNumber(row, column) {
        this.$emit('convert-to-number', row, column);
      }
    }
  };
  export default{
    created () {
      that = this;
      that.getStorageData();
      that.getBuyerData();
    },
    components: {
      PcDialog, AppSalePView, BillDetail
    },
    data () {
      return {
        isAppSalPre: false,
        isBillDetail: false,
        clearable: true,
        storageId: null,
        form: {
          arType: 1, // 交易类型(1:出售 2:回购)
          repurchaseDays: '',
          storageId: null,
          storageName: '',
          buyerId: null,
          buyerName: ''
        },
        tableData: [],
        selTableData: [],
        spanArr: [],
        position: 0,
        previewData: [],
        storageOption: [],
        buyerOption: [],
        goodsColumns: [
          {label: '仓单业务号', prop: 'busNo'},
          {label: '货物名称', prop: 'goodsName'},
          {label: '柜号', prop: 'cntrNo'},
          {label: '生产厂家', prop: 'vendor'},
          {label: '原产地', prop: 'countryOrigin'},
          {label: '包装', prop: 'packageDesc'},
          {label: '生产日期', prop: 'productDate'},
          {label: '库存数量', prop: 'wsStockNum'},
          {label: '可用库存数量', prop: 'wsLeftNum'},
          {label: '单位', prop: 'unitDesc'},
          {label: '出售数量', prop: 'sellNum'},
          {label: '对应仓单', prop: 'wrId'}
        ],
        columnsSchema: {
          '仓单业务号': { minWidth: 180 },
          '货物名称': { minWidth: 180 },
          '柜号': { minWidth: 150 },
          '生产厂家': { minWidth: 100 },
          '原产地': { minWidth: 120 },
          '包装': { minWidth: 80 },
          '生产日期': { minWidth: 150 },
          '库存数量': { minWidth: 80 },
          '可用库存数量': { minWidth: 150 },
          '单位': { minWidth: 60 },
          '出售数量': {
            minWidth: 150,
            fixed: 'right',
            component: Editor, // 'el-input'
            listeners: {
              'verify-integer' (row, column) {
                mValidate.verifyInteger(row, column.property);
                let wsLeftNum = row.wsLeftNum;
                let sellNum = row.sellNum;
                if (sellNum > wsLeftNum) {
//                  that.errorTip('出售数量不能大于可用库存数量');
                }
                if (sellNum === 0 || sellNum === '') {
//                  that.errorTip('出售数量需要大于0');
                }
              },
              'convert-to-number' (row, column) {
                row[column.property] = mValidate.convertToNumber(row[column.property]);
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          },
          '对应仓单': {
            label: '对应仓单',
            width: 116,
            merge: true,
            fixed: 'right',
            component: Btn, // 'el-button'
            listeners: {
              'view-detail' (data) {
//                console.log('custom-event: ', JSON.stringify(data));
                that.wrId = data.wrId; // 仓单ID
                that.isBillDetail = true;
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        },
        columnsProps: {
          height: 40,
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true
        },
        wrId: null, // 仓单ID,
        noData: false,
        rules: {
          // buyerId repurchaseDays
          storageId: [
            { required: true, message: '请选择仓库', trigger: 'change' }
          ],
          buyerId: [
            { required: true, message: '请选择交易对象', trigger: 'change' }
          ],
          repurchaseDays: [
            { required: true, message: '请输入回购期限', trigger: 'change' },
            { validator: mValidate.checkBuyDay, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      // 页面预览
      toPreview () {
        // 校验进入预览页面的条件
        let valid = this.checkCondition();
        if (valid) {
          // 处理要传给预览页面的数据
          this.previewData = this.PreData();
          for (var i = 0; i < this.previewData.length; i++) {
            // 计算 参考出售数量  参考出售重量=入库平均重量*出售数量
            this.previewData[i].referPrice = this.previewData[i].refAvgWeight * this.previewData[i].sellNum;
            this.previewData[i].referPrice = Number(this.previewData[i].referPrice).toFixed(2);
          }
          this.isAppSalPre = true;
        }
      },
      objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 12) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
      },
      rowspan () {
        this.tableData.forEach((item, index) => {
          if (index === 0) {
            this.spanArr.push(1);
            this.position = 0;
          } else {
            if (this.tableData[index].wrId === this.tableData[index - 1].wrId) {
              this.spanArr[this.position] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.position = index;
            }
          }
        });
      },
      // 仓单详情
      toDetail (index, row) {
        this.storageId = row.wrId;
        this.isBillDetail = true;
      },
      // 处理货物点击事件
      handleSelectionChange (selection) {
        let tableDataLength = this.tableData.length;
        for (var i = 0; i < tableDataLength; i++) {
          var j = 0;
          for (; j < selection.length; j++) {
            if (selection[j].wrGoodsId === this.tableData[i].wrGoodsId) {
              this.tableData[i].selected = true;
              break;
            }
          }
          if (j === selection.length) {
            this.tableData[i].selected = false;
          }
        }
      },
      // 校验输入的出售数量
      checkSellNum (index, oldVal, newVal) {
        let reg = /^[0-9]*[1-9][0-9]*$/;
        if (reg.test(newVal)) {
          if (newVal > oldVal || newVal === 0) {
            this.tableData[index].sellNum = oldVal;
          }
        } else {
          this.tableData[index].sellNum = oldVal;
        }
      },
      // 预览条件检测
      checkCondition () {
        let topCheck = true;
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            topCheck = false;
          };
        });
        if (!topCheck) {
          return false;
        }
        let goodData = this.PreData();
        if (goodData.length === 0) {
          this.errorTip('请选择要出售的货物');
          return false;
        }
        let checkNum = true;
        for (var i = 0; i < goodData.length; i++) {
          if (goodData[i].sellNum === null || goodData[i].sellNum === 0) {
            this.errorTip('出售数量需要大于0');
            checkNum = false;
            break;
          }
          if (goodData[i].sellNum > goodData[i].wsLeftNum) {
            this.errorTip('出售数量不能大于可用库存数量');
            checkNum = false;
            break;
          }
        }
        if (!checkNum) {
          return false;
        }
        return true;
      },
      // 回购期限 条件
      checkDays () {
        // this.form.repurchaseDays
//        this.form.repurchaseDays = this.form.repurchaseDays.replace(/^(0+)|[^\d]+/g, '');
//        if (this.form.repurchaseDays === '') {
//          this.errorTip('请输入回购期限');
//          return;
//        }
//        if (this.form.repurchaseDays < 15) {
//          this.errorTip('回购期限不能小于15天');
//        }
//        if (this.form.repurchaseDays > 90) {
//          this.errorTip('回购期限不能大于90天');
//        }
      },
      PreData () {
        let tempData = [];
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].selected) {
            tempData.push(this.tableData[i]);
          }
        }

        if (this.storageOption.length > 0) {
          for (var j = 0; j < this.storageOption.length; j++) {
            if (this.form.storageId === this.storageOption[j].id) {
              this.form.storageName = this.storageOption[j].storageName;
            }
          }
        }
        if (this.buyerOption.length > 0) {
          for (var k = 0; k < this.buyerOption.length; k++) {
            if (this.form.buyerId === this.buyerOption[k].buyerId) {
              this.form.buyerName = this.buyerOption[k].buyerName;
            }
          }
        }
        return tempData;
      },
      // 获取仓库Option数据
      getStorageData () {
        let that = this;
        that.ajax({
          url: '/maliwms/storage/selectStorage',
          type: 'POST',
          data: {},
          loading: false,
          success: (res) => {
            setTimeout(() => {
              that.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.storageOption = res.result;
            }
          }
        });
      },
      // 获取交易对象数据
      getBuyerData () {
        let that = this;
        that.ajax({
          url: '/maliwms/ar/getFinancingCompanyInfoListByLoginUser',
          type: 'GET',
          loading: false,
          success: (res) => {
            setTimeout(() => {
              that.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.buyerOption = res.result;
            } else {
              this.buyerOption = [];
            }
          }
        });
      },
      // 根据仓库id获取货物列表
      getTableData () {
        console.log(this.form.storageId);
        if (this.form.storageId === '') {
          this.tableData = [];
          this.noData = false;
          return;
        }
        let that = this;
        that.ajax({
          url: '/maliwms/ar/getSellWrGoodsList/?storageId=' + this.form.storageId,
          type: 'GET',
          loading: false,
          success: (res) => {
            setTimeout(() => {
              that.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              for (var i = 0; i < res.result.length; i++) {
                res.result[i].selected = false;
              }
              this.tableData = res.result;
              if (this.tableData.length === 0) {
                this.noData = true;
              } else {
                this.noData = false;
              }
              this.rowspan();
            }
          }
        });
      },
      closeRefresh () {
        this.isAppSalPre = false;
        this.$emit('closeRefresh', 'appSale');
      }
    }
  };
</script>
<style>
  .page-appsale .el-form{
    height: 100%;
    border: 1px solid #e5e5e5;
    background: #fff;
    padding-bottom: 30px;
  }
  .page-appsale .title{
    font-size:16px!important;
    color:#333333;
    border-bottom:1px solid #e5e5e5;
    background:#fff;
    height: 50px;
    line-height:50px;
    padding-left:20px;
    margin-bottom:20px;
  }
  .page-appsale .sale-item .el-form-item{
    width:45.7%;
    display:inline-block;
    margin-left:2.6%
  }
  .page-appsale .sale-item .el-input--small{
    width:100%;
    display:inline-block;
  }
  .page-appsale .el-select.el-select--small{
    width:100%;
  }
  .page-appsale .el-form-item__label {
    padding-bottom: 0;
    font-size: 14px;
  }
  .page-appsale .el-form-item--small.el-form-item {
    margin-bottom: 12px;
  }
  .page-appsale .ml-btn-default, .ml-btn-default:hover {
    min-width: 140px;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    margin: 0 5px;
    background-color: #1383f2;
    border-radius: 2px;
    color: #fff;
    font-size: 16px;
    text-align: center;
    display: inline-block;
    text-decoration: none;
    outline: none;
    cursor: pointer;
    border: none;
    position: relative;
    z-index: 10;
  }
  .page-appsale .submit-btn-box{
    text-align:center;
    margin-top:50px;
    margin-bottom:50px;
  }
  .page-appsale .appsale-box .appsale-title {
    font-size:16px!important;
    color:#333333;
    border:1px solid #ebeef5;
    background:#fff;
    height: 50px;
    line-height:50px;
    padding-left:20px;
    margin-top:26px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin-bottom:-1px;
  }
  .page-appsale .el-input.el-input--small.is-disabled{
    display:none;
  }
  .page-appsale .el-table--enable-row-transition .el-table__body td{
    line-height:49px;
    height:49px;
  }
  .page-appsale .el-table tr th:first-child .cell .el-checkbox{
    display:none;
  }
  .page-appsale .appsale-table{
    max-height:300px;
  }
  .mb50{
    margin-bottom:50px;
  }
  .no-data{
    text-align:center;
    height: 40px;
    line-height:40px;
  }
  .page-appsale table td .cell{
    text-align: center;
  }
</style>
